/*
  This file is part of the ArduinoRS485 library.
  Copyright (c) 2018 Arduino SA. All rights reserved.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2.1 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with this library; if not, write to the Free Software
  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
*/

#ifndef RS485_H_INCLUDED
#define RS485_H_INCLUDED

#include <Arduino.h>
#include"rtos.h"
#include "kSerial.h"

#ifdef PIN_SERIAL1_TX
#define RS485_DEFAULT_TX_PIN PIN_SERIAL1_TX
#else
#define RS485_DEFAULT_TX_PIN 1
#endif

#ifdef __AVR__
#define RS485_DEFAULT_DE_PIN 2
#define RS485_DEFAULT_RE_PIN -1
#else
#define RS485_DEFAULT_DE_PIN A6
#define RS485_DEFAULT_RE_PIN A5
#endif

class RS485Class : public kSerial {
public:
    RS485Class(int8_t txPin, int8_t rx_pin, int8_t dePin, int8_t rePin);

    int begin(unsigned int baud, u8 config = SERIAL_8N1, int rx_buff_sz = 256, int tx_buff_sz = 256) override;

    int end() override;

//    using Print::write; // pull in write(str) and write(buf, size) from Print
    void beginTransmission();

    u8 endTransmission() final;

    void receive();

    void noReceive();

    void sendBreak(unsigned int duration);

    void sendBreakMicroseconds(unsigned int duration);

    void setPins(int txPin, int dePin, int rePin);

    int write(const u8 *buffer, int size) override;

private:
    // HardwareSerial* _serial;
    int8_t _txPin;
    int8_t _dePin;
    int8_t _rePin;

    bool _transmisionBegun;

    static int _tx_complete_irq(serial_t *arg);
};

#endif
